package com.example.reader.ui.read.presenter;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;

/**
 * Created by Administrator on 2017/3/17.
 */

public class FileHandler {

    private final String filePath;
    private MappedByteBuffer buffer;
    private RandomAccessFile accessFile;

    public FileHandler(String filePath) {
        this.filePath = filePath;
        File file = new File(filePath);
        try {
            accessFile = new RandomAccessFile(file, "r");
            buffer = accessFile.getChannel().map(FileChannel.MapMode.READ_ONLY, 0, file.length() - 1);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public long getFileLength(){
        try {
            return accessFile.length();
        } catch (IOException e) {
            e.printStackTrace();
            return -1;
        }
    }


    /**
     * 读取上一段落
     *
     * @param curEndPos 当前页结束位置指针
     * @return
     */
    public byte[] readParagraphBefore(int curEndPos) {
        byte b0;
        int i = curEndPos;
        while (i > 0) {
            b0 = buffer.get(i--);
            if (b0 == 0x0a && (i + 2) != curEndPos) {
                i += 2;
                break;
            }
        }
        int nParaSize = curEndPos - i;
        byte[] buf = new byte[nParaSize];
        for (i = 0; i < nParaSize; i++) {
            buf[nParaSize - i - 1] = buffer.get(curEndPos - i - 1);
        }
        return buf;
    }

    /**
     * 读取下一段落
     *
     * @param curEndPos 当前页结束位置指针
     * @return
     */
    public byte[] readParagraphForward(int curEndPos) {
        byte b0;
        int i = curEndPos;
        while (i < buffer.limit()) {
            b0 = buffer.get(i);
            i++;
            if (b0 == 0x0a) {
                break;
            }
        }
        int nParaSize = i - curEndPos;
        byte[] buf = new byte[nParaSize];
        for (i = 0; i < nParaSize; i++) {
            buf[i] = buffer.get(curEndPos + i);
        }
        return buf;
    }

}
